<template>
    <div class="from">
        <div class="formTip">
            <van-image :src="img"></van-image>
            <p>我们将以短信或电话的形式将验证码发送给您</p>
        </div>
        <van-field v-model="telcode" clearable label="验证码" placeholder="请输入验证码">
            <template #button>
                <van-button @click="sendCodeFn" :disabled="time < 10">{{ text }}</van-button>
            </template>
        </van-field>
        <div class="my-button">
            <van-button type="danger" :disabled="flag" block @click="checkTel">下一步</van-button>
        </div>
    </div>
</template>
<script>
import Vue from "vue";
import { Field, Button, Image as VanImage, Toast } from "vant";

import { doSendCode, doCheckCode } from "@/api/user";
Vue.use(Toast);
Vue.use(Button);
Vue.use(Field);
Vue.use(VanImage);
export default {
    data() {
        return {
            text: "发送验证码",
            telcode: "",
            img: "",
            time: 10, //  10S
            timer: null //  计时器
        };
    },
    methods: {
        checkTel() {
            // this.$router.push("/register/step3");
            doCheckCode({
                tel: localStorage.getItem('tel'),
                telcode: this.telcode
            }).then(res => {
                // console.log(res);
                if (res.code == '10007') {
                    Toast('验证码输入错误')
                } else {
                    this.$router.push('/register/step3')
                }
            })
        },
        sendCodeFn() {
            doSendCode({ tel: localStorage.getItem('tel') })
                .then(res => {
                    console.log(res);
                    Toast(res.message)
                    // 倒计时
                    this.timer = setInterval(() => {
                        this.text = this.time + 's后重新获取'
                        this.time--
                        if (this.time == -1) {
                            // 清空定时器
                            clearInterval(this.timer)
                            this.time = 10
                            this.text = '发送验证码'
                        }
                    }, 1000)

                })
        }
    },
    computed: {
        flag() {
            // 如果验证码没问题就直接返回一个 true 否则 false
            if (this.telcode.length == 5) {
                return false;
            } else {
                return true;
            }
        },
    },
};
</script>
<style>
.formTip {
    display: flex;
    height: 200px;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
</style>
